package com.xiehao.springbootmybaits.controller;

import com.github.pagehelper.PageInfo;
import com.xiehao.springbootmybaits.dao.BookMapper;
import com.xiehao.springbootmybaits.entity.Book;
import com.xiehao.springbootmybaits.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
@RequestMapping("/book")
public class BookController {

    @Autowired
    BookService bookService;

    @GetMapping
    public String getAll(Model model){
        List<Book> list = bookService.getAll();
        model.addAttribute("books",list);
        return "booklist";
    }

    @GetMapping("/page")
    public String getPage(@RequestParam(defaultValue = "1") Integer pageNum,Model model){
      PageInfo<Book> pageInfo =  bookService.getPage(pageNum);
      model.addAttribute("page",pageInfo);
      return "bookPage";
    }

    @PostMapping("/del")
    public String del(Integer[] ids){
        if (ids.length>0){
            bookService.del(ids);
        }
        return "redirect:/book/page";
    }

    @PostMapping("/addBook")
    public String addBook(Book book){
        bookService.addBook(book);
        return "redirect:/book/page";
    }

    @GetMapping("/add")
    public String add(){
        return "add";
    }

    @GetMapping("/searchBooks")
    public String searchBooks(Book book,Model model){
        List<Book> books = bookService.searchBooks(book);
        model.addAttribute("books",books);
        return "bookPage";
    }
}
